package com.echatim.service.app;

import com.annotation.MethodFor;
import com.annotation.TopicFor;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.broker.base.protocol.response.Resp;
import com.commom.AppRespError;
import com.commom.DBConst;
import com.commom.Topic;
import com.echatim.broker.localbroadcast.SystemMessageLocalBroadcastEvent;
import com.echatim.dto.UserApplyRecordsDTO;
import com.echatim.dto.UserBlackForbidListDTO;
import com.echatim.dto.UserFriendGetDTO;
import com.echatim.dto.UserFriendListDTO;
import com.echatim.entity.ApplyRecord;
import com.echatim.entity.Message;
import com.echatim.entity.User;
import com.echatim.entity.UserRelation;
import com.echatim.form.*;
import com.echatim.mapper.MessageMapper;
import com.echatim.mapper.UserRelationMapper;
import com.exception.ServiceException;
import com.utils.Beans;
import com.utils.Streams;
import com.utils.UIDUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.Valid;
import java.util.*;

/**
 * @author kong <androidsimu@163.com>
 * create by 2019/2/21 13:21
 * Description: echatim
 **/


@Slf4j
@TopicFor(value = Topic.APP_USER_RELATION.name)
@DS("master")
@Service
public class UserRelationService extends ServiceImpl<UserRelationMapper, UserRelation>  {
    @Autowired
    private UserService userService;
    @Autowired
    private ApplyRecordService applyRecordService;
    @Autowired
    private SystemMessageService systemMessageService;
    @Autowired
    private MessageMapper messageMapper;

    @MethodFor(value = Topic.APP_USER_RELATION.METHOD.ADD_FRIEND, consumer = UserFriendAddForm.class)
    @Transactional
    public Resp<String> addFriend(@Valid UserFriendAddForm userFriendAddForm){
        DBConst.AddFriendType friendType = DBConst.AddFriendType.of(userFriendAddForm.getType());
        if(friendType == null){
            return Resp.failed("type必须为ADD,APPLY,AGREE,REJECT 其中之一", AppRespError.RELATION_TYPE.getCode());
        }
        Resp<String> checkResp = checkFriendAuid(userFriendAddForm.getAuid(), userFriendAddForm.getTargetAuid());
        if(!checkResp.ok()){
            return checkResp;
        }
        // 之前已存在的数据
        UserRelation existUserRelation = this.lambdaQuery()
                .eq(UserRelation::getAuid, userFriendAddForm.getAuid())
                .eq(UserRelation::getTargetAuid, userFriendAddForm.getTargetAuid())
                .one();
        if(DBConst.AddFriendType.ADD.name().equals(friendType.name())){
            this.saveOrUpdate(Beans.copy(userFriendAddForm, UserRelation.class)
                    .setId(existUserRelation == null ? null : existUserRelation.getId())
                    .setUid(UIDUtils.gen())
                    .setType("FRIEND")
                    .setApplyText(userFriendAddForm.getApplyText())
                    .setStatus(DBConst.EntryStatus.NORMAL.name())
                    .setCreateTime(new Date()));
            saveTargetUserFriend(userFriendAddForm);
            return Resp.ok("添加成功");
        }

        List<User> users = userService.lambdaQuery().in(User::getAuid, Arrays.asList(userFriendAddForm.getAuid(), userFriendAddForm.getTargetAuid())).list();
        Map<String, User> userMapByAuid = Streams.toMapByKey(users, v->v.getAuid());
        if(DBConst.AddFriendType.APPLY.name().equals(friendType.name())){
            if(existUserRelation != null){
                return Resp.failed("该用户已是你好友.");
            }
            User originUser = userMapByAuid.getOrDefault(userFriendAddForm.getAuid(), new User());
            User targetUser = userMapByAuid.getOrDefault(userFriendAddForm.getTargetAuid(), new User());
            ApplyRecord applyRecord = new ApplyRecord();
            applyRecord.setFromId(userMapByAuid.getOrDefault(userFriendAddForm.getAuid(), new User()).getId());
            applyRecord.setToId(userMapByAuid.getOrDefault(userFriendAddForm.getTargetAuid(), new User()).getId());
            applyRecord.setAttachText(userFriendAddForm.getApplyText());
            applyRecord.setStatus(DBConst.ApplyRecordStatus.NORMAL.name());
            applyRecord.setSource("ADD_FRIEND");
            applyRecord.setCreateTime(new Date());
            ApplyRecord record = applyRecordService.lambdaQuery()
                    .eq(ApplyRecord::getStatus, DBConst.ApplyRecordStatus.NORMAL.name())
                    .eq(ApplyRecord::getFromId, applyRecord.getFromId())
                    .eq(ApplyRecord::getToId, applyRecord.getToId())
                    .one();
            if(record != null){
                return Resp.failed("你已存在申请好友的记录.");
            }
            applyRecordService.save(applyRecord);
            // 加入系统消息
//            String body = Beans.json(new HashMap<String, Object>(){{
//                put("body", String.format("%s申请添加你为好友", originUser.getName()));
//            }});
//            SystemMessage systemMessage = new SystemMessage()
//                    .setUid(UIDUtils.gen())
//                    .setAppKey(targetUser.getAppKey())
//                    .setBody(body).setStatus(DBConst.EntryStatus.NORMAL.name())
//                    .setToTarget(targetUser.getAuid())
//                    .setType("TEXT")
//                    .setCategory(DBConst.SystemMessageCategory.APPLY_FRIEND.name())
//                    .setCreateTime(new Date());
//            systemMessageService.save(systemMessage);
            List<Long> systemMessageIds = new ArrayList<>();
            systemMessageIds.add(systemMessageService.saveSystemMessage(originUser, targetUser, DBConst.SystemMessageCategory.APPLY_FRIEND.name(), String.format("%s申请添加你为好友", originUser.getName())));
            systemMessageService.localBroadcast(new SystemMessageLocalBroadcastEvent().setIds(systemMessageIds));
        }


        return Resp.ok("添加成功");
    }


    private void saveTargetUserFriend(UserFriendAddForm userFriendAddForm){
        // 自己成为对方的好友
        int cnt = this.lambdaQuery()
                .eq(UserRelation::getAuid, userFriendAddForm.getTargetAuid())
                .eq(UserRelation::getTargetAuid, userFriendAddForm.getAuid())
                .count();
        if(cnt == 0){
            this.save(new UserRelation()
                    .setUid(UIDUtils.gen())
                    .setAuid(userFriendAddForm.getTargetAuid())
                    .setTargetAuid(userFriendAddForm.getAuid())
                    .setType("FRIEND")
                    .setApplyText("")
                    .setStatus(DBConst.EntryStatus.NORMAL.name())
                    .setCreateTime(new Date()));
        }
    }


    @MethodFor(value = Topic.APP_USER_RELATION.METHOD.DEL_FRIEND, consumer = UserFriendAddForm.class)
    public Resp<String> delFriend(@Valid UserFriendDelForm userFriendDelForm){
        Resp<String> checkResp = checkFriendAuid(userFriendDelForm.getAuid(), userFriendDelForm.getTargetAuid());
        if(!checkResp.ok()){
            return checkResp;
        }
//        this.lambdaUpdate()
//                .set(UserRelation::getStatus, DBConst.AddFriendStatus.DEL.name())
//                // where
//                .eq(UserRelation::getAuid, userFriendDelForm.getAuid())
//                .eq(UserRelation::getTargetAuid, userFriendDelForm.getTargetAuid())
//                .eq(UserRelation::getStatus, DBConst.AddFriendStatus.NORMAL.name())
//                .update();
        // 物理删除，清除自己的关系数据
        this.remove(Wrappers.<UserRelation>lambdaQuery()
                .eq(UserRelation::getAuid, userFriendDelForm.getAuid())
                .eq(UserRelation::getTargetAuid, userFriendDelForm.getTargetAuid())
                .eq(UserRelation::getStatus, DBConst.AddFriendStatus.NORMAL.name())
                .eq(UserRelation::getType, "FRIEND")
        );
        // 物理删除，清除对方的关系数据
        this.remove(Wrappers.<UserRelation>lambdaQuery()
                .eq(UserRelation::getAuid, userFriendDelForm.getTargetAuid())
                .eq(UserRelation::getTargetAuid, userFriendDelForm.getAuid())
                .eq(UserRelation::getStatus, DBConst.AddFriendStatus.NORMAL.name())
                .eq(UserRelation::getType, "FRIEND")
        );
        // 物理删除，清除用户之间的会话
        messageMapper.delete(Wrappers.<Message>lambdaQuery()
                .eq(Message::getFromUser, userFriendDelForm.getAuid())
                .eq(Message::getToTarget, userFriendDelForm.getTargetAuid())
                .eq(Message::getWay, DBConst.MessageWay.P2P.name())
        );
        messageMapper.delete(Wrappers.<Message>lambdaQuery()
                .eq(Message::getFromUser, userFriendDelForm.getTargetAuid())
                .eq(Message::getToTarget, userFriendDelForm.getAuid())
                .eq(Message::getWay, DBConst.MessageWay.P2P.name())
        );
        User originUser = Optional.ofNullable(userService.lambdaQuery().eq(User::getAuid, userFriendDelForm.getAuid()).one()).orElseThrow(()->new ServiceException("用户不存在,auid=" + userFriendDelForm.getAuid()));
        User targetUser = Optional.ofNullable(userService.lambdaQuery().eq(User::getAuid, userFriendDelForm.getTargetAuid()).one()).orElseThrow(()->new ServiceException("被删除的用户不存在,rid=" + userFriendDelForm.getTargetAuid()));
        List<Long> systemMessageIds = new ArrayList<>();
        systemMessageIds.add(systemMessageService.saveSystemMessage(originUser, originUser, DBConst.SystemMessageCategory.DELETE_FRIEND.name(), String.format("你已删除了好友:%s", targetUser.getName())));
        systemMessageIds.add(systemMessageService.saveSystemMessage(originUser, targetUser, DBConst.SystemMessageCategory.DELETE_FRIEND.name(), String.format("%s已从好友列表中把你移除", originUser.getName())));
        systemMessageService.localBroadcast(new SystemMessageLocalBroadcastEvent().setIds(systemMessageIds));

        return Resp.ok("处理成功");
    }


    @MethodFor(value = Topic.APP_USER_RELATION.METHOD.LIST_FRIENDS, consumer = UserFriendListForm.class)
    public Resp<List<UserFriendListDTO>> listFriend(@Valid UserFriendListForm userFriendListForm){
       int cnt  = userService.lambdaQuery().eq(User::getAuid, userFriendListForm.getAuid()).count();
       if(cnt == 0){
           return Resp.failed("用户auid不存在:" + userFriendListForm.getAuid(), AppRespError.AUID_NOT_EXIST.getCode());
       }
       List<UserRelation> relations = this.lambdaQuery()
               .eq(UserRelation::getAuid, userFriendListForm.getAuid())
               .ne(UserRelation::getStatus, DBConst.EntryStatus.DEL.name())
               .eq(userFriendListForm.getUpdatetime() > 1, UserRelation::getCreateTime, userFriendListForm.getUpdatetime())
               .list();
        List<String> userAuids = Streams.keys(relations, v->v.getTargetAuid());
        if(userAuids.isEmpty()){
            return Resp.ok(Collections.emptyList());
        }
        List<User> users = userService.lambdaQuery()
                .in(User::getAuid, userAuids)
                .list();
        Map<String, User> usersMapByAuid= Streams.toMapByKey(users, User::getAuid);

        List<UserFriendListDTO> dtos = Streams.map(relations, v->Beans.copy(v, UserFriendListDTO.class)
                .setAuid(v.getTargetAuid())
                .setName(usersMapByAuid.getOrDefault(v.getTargetAuid(), new User()).getName())
                .setNamePinyin(usersMapByAuid.getOrDefault(v.getTargetAuid(), new User()).getNamePinyin())
                .setAvatar(usersMapByAuid.getOrDefault(v.getTargetAuid(), new User()).getAvatar())
                .setSign(usersMapByAuid.getOrDefault(v.getTargetAuid(), new User()).getSign())
                .setAlias(v.getAlias()));
        return Resp.ok(dtos);
    }


    @MethodFor(value = Topic.APP_USER_RELATION.METHOD.GET_FRIEND, consumer = UserFriendGetForm.class)
    public Resp<UserFriendGetDTO> getFriend(@Valid UserFriendGetForm getForm){
        UserRelation existUserRelation = this.lambdaQuery()
                .eq(UserRelation::getAuid, getForm.getAuid())
                .ne(UserRelation::getStatus, DBConst.EntryStatus.DEL.name())
                .eq(UserRelation::getTargetAuid, getForm.getTargetAuid())
                .one();
        if(existUserRelation == null){
            return Resp.failed(String.format("无法找到好友信息:auid = %s, friendAuid = %s", getForm.getAuid(), getForm.getTargetAuid()), AppRespError.FRIEND_NOT_FOUND.getCode());
        }
        User friend  = userService.lambdaQuery().eq(User::getAuid, getForm.getTargetAuid()).one();
        if(friend == null){
            return Resp.failed(String.format("无法找到好友信息:auid = %s", getForm.getAuid()), AppRespError.FRIEND_NOT_FOUND.getCode());
        }
        UserFriendGetDTO dto =  Beans.copy(friend, UserFriendGetDTO.class)
                .setBlacklist(existUserRelation.getBlacklist())
                .setForbid(existUserRelation.getForbid())
                .setAlias(existUserRelation.getAlias())
                .setCreateTime(existUserRelation.getCreateTime());

        return Resp.ok(dto);
    }



    @MethodFor(value = Topic.APP_USER_RELATION.METHOD.MODIFY_BLACKLIST_FORBID, consumer = UserBlacklistModifyForm.class)
    public Resp<String> modifyBlacklistForbid(@Valid UserBlacklistModifyForm userBlacklistModifyForm){
        DBConst.ModifyBlacklistType blacklistType = DBConst.ModifyBlacklistType.of(userBlacklistModifyForm.getType());
        if(blacklistType == null){
            return Resp.failed("type必须为ADD_BLACKLIST,ADD_FORBID,REMOVE_BLACKLIST,REMOVE_FORBID 其中之一", AppRespError.BLACKLIST_TYPE.getCode());
        }
        Resp<String> checkResp = checkFriendAuid(userBlacklistModifyForm.getAuid(), userBlacklistModifyForm.getTargetAuid());
        if(!checkResp.ok()){
            return checkResp;
        }
        if(DBConst.ModifyBlacklistType.ADD_BLACKLIST.name().equals(blacklistType.name())){
            this.lambdaUpdate()
                    .set(UserRelation::getBlacklist, 1)
                    // where
                    .eq(UserRelation::getAuid, userBlacklistModifyForm.getAuid())
                    .eq(UserRelation::getTargetAuid, userBlacklistModifyForm.getTargetAuid())
                    .eq(UserRelation::getStatus,  DBConst.AddFriendStatus.NORMAL.name())
                    .update();
        }
        else if(DBConst.ModifyBlacklistType.ADD_FORBID.name().equals(blacklistType.name())){
            this.lambdaUpdate()
                    .set(UserRelation::getForbid, 1)
                    // where
                    .eq(UserRelation::getAuid, userBlacklistModifyForm.getAuid())
                    .eq(UserRelation::getTargetAuid, userBlacklistModifyForm.getTargetAuid())
                    .eq(UserRelation::getStatus,  DBConst.AddFriendStatus.NORMAL.name())
                    .update();
        }else if(DBConst.ModifyBlacklistType.REMOVE_BLACKLIST.name().equals(blacklistType.name())){
            this.lambdaUpdate()
                    .set(UserRelation::getBlacklist, 0)
                    // where
                    .eq(UserRelation::getAuid, userBlacklistModifyForm.getAuid())
                    .eq(UserRelation::getTargetAuid, userBlacklistModifyForm.getTargetAuid())
                    .eq(UserRelation::getStatus,  DBConst.AddFriendStatus.NORMAL.name())
                    .update();
        }
        else if(DBConst.ModifyBlacklistType.REMOVE_FORBID.name().equals(blacklistType.name())){
            this.lambdaUpdate()
                    .set(UserRelation::getForbid, 0)
                    // where
                    .eq(UserRelation::getAuid, userBlacklistModifyForm.getAuid())
                    .eq(UserRelation::getTargetAuid, userBlacklistModifyForm.getTargetAuid())
                    .eq(UserRelation::getStatus,  DBConst.AddFriendStatus.NORMAL.name())
                    .update();
        }


        return Resp.ok("处理成功");
    }




    @MethodFor(value = Topic.APP_USER_RELATION.METHOD.LIST_BLACKLIST_FORBID, consumer = UserFriendListForm.class)
    public Resp<UserBlackForbidListDTO> listBlackForbid(@Valid UserBlackForbidListForm userBlackForbidListForm){
        int cnt  = userService.lambdaQuery().eq(User::getAuid, userBlackForbidListForm.getAuid()).count();
        if(cnt == 0){
            return Resp.failed("用户auid不存在:" + userBlackForbidListForm.getAuid(), AppRespError.AUID_NOT_EXIST.getCode());
        }
        // 黑名单
        List<UserRelation> blacklists = this.lambdaQuery()
                .eq(UserRelation::getAuid, userBlackForbidListForm.getAuid())
                .ne(UserRelation::getStatus, DBConst.EntryStatus.DEL.name())
                .eq(UserRelation::getBlacklist, 1)
                .list();
        // 禁言名单
        List<UserRelation> forbids = this.lambdaQuery()
                .eq(UserRelation::getAuid, userBlackForbidListForm.getAuid())
                .ne(UserRelation::getStatus, DBConst.EntryStatus.DEL.name())
                .eq(UserRelation::getForbid, 1)
                .list();
        List<String> userAuids = new ArrayList<String>(){{
            addAll(Streams.keys(blacklists, v->v.getTargetAuid()));
            addAll(Streams.keys(forbids, v->v.getTargetAuid()));
        }};
        if(userAuids.isEmpty()){
            return Resp.ok(new UserBlackForbidListDTO());
        }
        List<User> users = userService.lambdaQuery().in(User::getAuid, userAuids).list();
        Map<String, User> usersMapByAuids = Streams.toMapByKey(users, v->v.getAuid());
        List<UserFriendListDTO> forbidsDTO = Streams.map(forbids, v->{
            return Beans.copy(v, UserFriendListDTO.class)
                    .setAuid(v.getTargetAuid())
                    .setAlias(v.getAlias())
                    .setName(usersMapByAuids.getOrDefault(v.getTargetAuid(), new User()).getName())
                    .setNamePinyin(usersMapByAuids.getOrDefault(v.getTargetAuid(), new User()).getNamePinyin())
                    .setSign(usersMapByAuids.getOrDefault(v.getTargetAuid(), new User()).getSign())
                    .setAvatar(usersMapByAuids.getOrDefault(v.getTargetAuid(), new User()).getAvatar());
        });
        List<UserFriendListDTO> blacklistsDTO = Streams.map(blacklists, v->{
            return Beans.copy(v, UserFriendListDTO.class)
                    .setAuid(v.getTargetAuid())
                    .setAlias(v.getAlias())
                    .setName(usersMapByAuids.getOrDefault(v.getTargetAuid(), new User()).getName())
                    .setNamePinyin(usersMapByAuids.getOrDefault(v.getTargetAuid(), new User()).getNamePinyin())
                    .setSign(usersMapByAuids.getOrDefault(v.getTargetAuid(), new User()).getSign())
                    .setAvatar(usersMapByAuids.getOrDefault(v.getTargetAuid(), new User()).getAvatar());
        });
        UserBlackForbidListDTO blackForbidListDTO = new UserBlackForbidListDTO()
                .setBlacklists(blacklistsDTO)
                .setForbids(forbidsDTO);

        return Resp.ok(blackForbidListDTO);
    }


    private Resp<String> checkFriendAuid(String myauid, String targetAuid){
        List<User> checkUsers = userService.lambdaQuery().in(User::getAuid, Arrays.asList(myauid, targetAuid)).list();
        List<String> checkUserAuids = Streams.keys(checkUsers, v->v.getAuid());
        if(!checkUserAuids.contains(myauid)){
            return Resp.failed("用户auid不存在:" + myauid, AppRespError.AUID_NOT_EXIST.getCode());
        }
        if(!checkUserAuids.contains(targetAuid)){
            return Resp.failed("好友auid不存在:" + targetAuid, AppRespError.FRIEND_NOT_EXIST.getCode());
        }

        return Resp.ok("");
    }

    public Resp<String> modifyAlias(UserFriendAliasForm aliasForm) {
        UserRelation existUserRelation = this.lambdaQuery()
                .eq(UserRelation::getAuid, aliasForm.getAuid())
                .ne(UserRelation::getStatus, DBConst.EntryStatus.DEL.name())
                .eq(UserRelation::getTargetAuid, aliasForm.getTargetAuid())
                .one();
        if(existUserRelation == null){
            return Resp.failed(String.format("无法找到好友信息:auid = %s, friendAuid = %s", aliasForm.getAuid(), aliasForm.getTargetAuid()), AppRespError.FRIEND_NOT_FOUND.getCode());
        }
        existUserRelation.setAlias(aliasForm.getAlias());
        this.updateById(existUserRelation);

        return Resp.ok("");
    }


    @MethodFor(value = Topic.APP_USER_RELATION.METHOD.APPLY_RECORD, consumer = UserApplyRecordsForm.class)
    public Resp<List<UserApplyRecordsDTO>> applyRecord(@Valid UserApplyRecordsForm form){
        User currentUser = Optional.ofNullable(userService.lambdaQuery().eq(User::getAuid, form.getAuid()).one()).orElseThrow(()->new ServiceException("用户不存在,auid=" + form.getAuid()));
        List<ApplyRecord> records = applyRecordService.lambdaQuery()
                .eq(ApplyRecord::getToId, currentUser.getId())
                .eq(ApplyRecord::getStatus, DBConst.ApplyRecordStatus.NORMAL.name())
                .eq(ApplyRecord::getSource, DBConst.ApplyRecordSource.ADD_FRIEND.name())
                .orderByDesc(ApplyRecord::getCreateTime)
                .list();
        List<Long> userIds = new ArrayList<Long>(){{
            addAll(Streams.ids(records, v->v.getFromId()));
            addAll(Streams.ids(records, v->v.getToId()));
        }};
        if(userIds.isEmpty()){
            return Resp.ok(new ArrayList<>());
        }
        List<User> users = userService.getBaseMapper().selectBatchIds(userIds);
        Map<Long, User> usersMapById= Streams.toMapById(users, User::getId);
        // 获取陌生人的详细信息
        List<UserApplyRecordsDTO> dtos = Streams.map(records, v->{
            User u = usersMapById.getOrDefault(v.getFromId(), new User());
            return new UserApplyRecordsDTO()
                    .setId(v.getId()) // 申请记录id
                    .setAuid(u.getAuid()) // 用户auid
                    .setAttachText(v.getAttachText()) // 附加文字
                    .setName(u.getName())
                    .setAvatar(u.getAvatar())
                    .setSign(u.getSign())
                    .setAlias(""); // 别名
        });
        return Resp.ok(dtos);
    }

    public Resp<Void> doApplyFriend(UserFriendAgreeForm form, String status) {
        UserRelation existUserRelation = this.lambdaQuery()
                .eq(UserRelation::getAuid, form.getAuid())
                .eq(UserRelation::getTargetAuid, form.getTargetAuid())
                .one();
        if (existUserRelation != null) {
            return Resp.failed("该用户已是好友.");
        }
        List<User> users = userService.lambdaQuery().in(User::getAuid, Arrays.asList(form.getAuid(), form.getTargetAuid())).list();
        Map<Long, User> userMapById = Streams.toMapById(users, v -> v.getId());
        Map<String, User> userMapByAuid = Streams.toMapByKey(users, v -> v.getAuid());
        ApplyRecord record = applyRecordService.getById(form.getApplyRecordId());
        if (record == null) {
            return Resp.failed("不存在申请记录.");
        }
        // 同意时添加好友关系记录
        if(DBConst.ApplyRecordStatus.FINISH.name().equals(status)){
            UserRelation userRelation = new UserRelation()
                    .setId(null)
                    .setUid(UIDUtils.gen())
                    .setAuid(userMapById.getOrDefault(record.getFromId(), new User()).getAuid())
                    .setTargetAuid(userMapById.getOrDefault(record.getToId(), new User()).getAuid())
                    .setType("FRIEND")
                    .setApplyText(record.getAttachText())
                    .setStatus(DBConst.EntryStatus.NORMAL.name())
                    .setCreateTime(new Date());
            this.save(userRelation);
            saveTargetUserFriend(Beans.copy(userRelation, UserFriendAddForm.class));

            User currentUser = userMapByAuid.getOrDefault(form.getAuid(), new User());
            User targetUser = userMapByAuid.getOrDefault(form.getTargetAuid(), new User());
//            String body = Beans.json(new HashMap<String, Object>(){{
//                put("body", String.format("%s已同意你为好友", currentUser.getName()));
//            }});
//            SystemMessage systemMessage = new SystemMessage()
//                    .setUid(UIDUtils.gen())
//                    .setAppKey(targetUser.getAppKey())
//                    .setBody(body).setStatus(DBConst.EntryStatus.NORMAL.name())
//                    .setToTarget(targetUser.getAuid())
//                    .setType("TEXT")
//                    .setCategory(DBConst.SystemMessageCategory.APPLY_FRIEND_AGREE.name())
//                    .setCreateTime(new Date());
//            systemMessageService.save(systemMessage);
            List<Long> systemMessageIds = new ArrayList<>();
            systemMessageIds.add(systemMessageService.saveSystemMessage(currentUser, currentUser, DBConst.SystemMessageCategory.APPLY_FRIEND_AGREE.name(), String.format("你已添加好友:%s", targetUser.getName())));
            systemMessageIds.add(systemMessageService.saveSystemMessage(currentUser, targetUser, DBConst.SystemMessageCategory.APPLY_FRIEND_AGREE.name(), String.format("%s已同意你为好友", currentUser.getName())));
            systemMessageService.localBroadcast(new SystemMessageLocalBroadcastEvent().setIds(systemMessageIds));
        }
        record.setStatus(status);

        applyRecordService.updateById(record);
        return Resp.ok(null);
    }

    @MethodFor(value = Topic.APP_USER_RELATION.METHOD.AGREE_FRIEND, consumer = UserFriendAgreeForm.class)
    public Resp<Void> agreeFriend(@Valid UserFriendAgreeForm form){
        return doApplyFriend(form, DBConst.ApplyRecordStatus.FINISH.name());
    }

    @MethodFor(value = Topic.APP_USER_RELATION.METHOD.REJECT_FRIEND, consumer = UserFriendAgreeForm.class)
    public Resp<Void> rejectFriend(@Valid UserFriendRejectForm form){
        return doApplyFriend(Beans.copy(form, UserFriendAgreeForm.class), DBConst.ApplyRecordStatus.REJECT.name());
    }
}
